package com.demo.Controller;



import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.entity.Book;
import com.demo.service.BookServiceimp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@org.springframework.stereotype.Controller
public class Controller {

    @Autowired
    BookServiceimp bookService;

    @RequestMapping("hello")
    public String hello(Model model){
        Page<Book> bookPage = new Page<>(1,3);
        bookPage = bookService.page(bookPage);
        model.addAttribute("page",bookPage);
        return "index";
    }


    @RequestMapping("cx")
    public String cx(Model model,String name){
        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper();
        if (!name.equals("")){
            queryWrapper.like(Book::getName,name);
        }
        Page<Book> bookPage = new Page<>(1,3);
        bookPage = bookService.page(bookPage,queryWrapper);
        model.addAttribute("page",bookPage);
        model.addAttribute("bookname",name);
        return "index";
    }

    @RequestMapping("page")
    public String cx(Model model,String name,int pagenum){
        Page<Book> bookPage = new Page<>(pagenum,3);
        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper();
        if (!name.equals("")){
            queryWrapper.like(Book::getName,name);
        }
        Page<Book> frst = bookService.page(bookPage,queryWrapper);
        model.addAttribute("page",frst);
        model.addAttribute("bookname",name);
        return "index";
    }

    @RequestMapping("del")
    public String del(int id){
        bookService.removeById(id);
        return "redirect:/hello";
    }

    @RequestMapping("delby")
    public String del(int[] id){
        List<Integer> list = new ArrayList<>();
        for (int i : id) {
            list.add(i);
        }
        int i = bookService.deleteBatchIds(list);
        return "redirect:/hello";
    }


    @RequestMapping("add")
    public String del(Book book){
            bookService.save(book);
        return "redirect:/hello";
    }


    @RequestMapping("add1")
    public String add1(){
        return "insert";
    }

    @RequestMapping("update")
    public String update(int id,Model model){
        Book book = bookService.getById(id);
        model.addAttribute("dan",book);
        return "update";
    }

    @RequestMapping("update1")
    public String update1(Book book1){
        bookService.updateById(book1);
        return "redirect:/hello";
    }


}
